package com.edu.internship.config.redis;


import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Resource

    private RedisTemplate<String, String> redisTemplate;

    /**
     * 存放键值对
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param time 时间
     * @param timeUnit 时间颗粒度 毫秒
     */
    public boolean set(String key,String value,long time){
        try{
            if(key != null){
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.MILLISECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 通过key获取value
     * @param key
     * @return
     */
    public String get(String key){
        try {
            if (key != null) {
                return redisTemplate.opsForValue().get(key);
            } else {
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据key值进行删除，可删除多个
     * @param key
     */
    public void del(String key){
        if (key != null) {
          redisTemplate.delete(key);
        }
    }

    /**
     * 从redis缓存中获取具有某个前缀的所有key
     * @param pattern
     * @return
     */
    public Map<String, Object> keys(String pattern){
        Set<String> set =redisTemplate.keys(pattern + "*");
        Map<String, Object> map = new HashMap<>();
        for(String ser : set){
            map.put(ser,get(ser));
        }
        return map;

    }

    /**
     * 从redis中删除具有某个前缀的所有缓存
     * @param pattern
     * @return
     */
    public boolean deleteKeys(String pattern){
        Set<String> keys = redisTemplate.keys(pattern + "*");
        redisTemplate.delete(keys);
        return true;
    }

}
